from flask import Flask, render_template, g
from flask_login import LoginManager, current_user
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login.login'
db = SQLAlchemy()
ma = Marshmallow()


def create_app(config):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        db.init_app(app)
        ma.init_app(ma)
        login_manager.init_app(app)
        from .routes import main_blueprint, wx_auth_blueprint, login_blueprint, \
            user_blueprint, chat_blueprint, setting_blueprint, role_blueprint
        app.register_blueprint(main_blueprint)
        app.register_blueprint(wx_auth_blueprint, url_prefix='/wx_auth')
        app.register_blueprint(login_blueprint)
        app.register_blueprint(user_blueprint, url_prefix='/user')
        app.register_blueprint(role_blueprint, url_prefix='/role')
        app.register_blueprint(chat_blueprint, url_prefix='/chat')
        app.register_blueprint(setting_blueprint, url_prefix='/setting')
        from .routes.upload import init_upload
        init_upload(app)

        @app.template_test('has_permission')
        def user_has_permission(menu_id):
            _has = False
            for menu in current_user.role.menus:
                if menu.menu_id == menu_id:
                    _has = True
            return _has

        @app.errorhandler(404)
        def page_not_found(e):
            return render_template('error/404.html'), 404

        @login_manager.user_loader
        def load_user(id):
            from .models.tables import User
            return User.query.get(int(id))

        @app.context_processor
        def admin_processor():
            from .processor.menu import admin_nav
            return admin_nav

    return app
